package cn.ichiva.util.ui;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

public class DrawCanvas extends Canvas implements Runnable {

	private static final long serialVersionUID = 1013024116064722280L;
	
	private Image offScreenImage;
	private Image image;
	private int _width;
	private int _height;
	
	private int i=0; //刷新数量
	public int fps = 0;

	public DrawCanvas(Image image,int width, int height) {
		this.image = image;
		this._width=width;
		this._height=height;
	}

	@Override
	public void paint(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		g2.drawImage(image, 0, 0, null);
		
		i++;
	}
	
	@Override
	public void run() {
		while(true){
			fps = i;
			i=0;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}
	}

	@Override
	public void update(Graphics g) {
		if(null == offScreenImage) offScreenImage = this.createImage(_width, _height); // 新建一个图像缓存空间,这里图像大小为800*600
		Graphics gImage = offScreenImage.getGraphics(); // 把它的画笔拿过来,给gImage保存着
		paint(gImage); // 将要画的东西画到图像缓存空间去
		g.drawImage(offScreenImage, 0, 0, null); // 然后一次性显示出来
	}
	
	public Image getImage() {
		return image;
	}
}